#!/usr/bin/perl
#
# Script to add/ remove entries to/from a file.
#
# The name of the edited file is assigned to the global variable $output_file.
#
# Syntax:  mkauthkeys [-a | -r | --add | --remove] <string>
#
#DJM

# Global Variables
#
$output_file = $ENV{HOME}."/.ssh/authorized_keys2";
$num_args = @ARGV;

if (! -w $output_file) {
   print("\n Error: $output_file does not exist or is unwriteable. \n\n");
   exit;
}

if ($num_args < 2) {
   &Usage;
   exit;
}

# Parse Arguments
#
$action = $ARGV[0];
shift @ARGV;
foreach $s (@ARGV) {
   $string = $string . $s;
   #print("\n string=$string");
}
#print("\n action=$action=  string=$string=\n");

# Append, remove or bail out.
#
if (($action eq "-a") || ($action eq "--add")) {
   &Append_String($string);
} elsif (($action eq "-r") || ($action eq "--remove")) {
   &Remove_String($string);
} else {
   &Usage;
}


sub Usage {
   print("\n\n  mkauthkeys [-a | -r | --add | --remove] <string>");
   print("\n\n  Where \"-a\" and \"--add\" adds ssh key");
   print(  "\n        \"-r\" and \"--remove\" removes key for the specified user id and host.");
   print(  "\n        \"string\" is the ssh key to add to, or the id@host to remove.\n\n");
   print(  "   Example:\n");
   print(  "     mkauthkeys -a 'adB8fqeZs2d-gg+q joe\@somehost'\n");
   print(  "        add ssh key generated for user joe at somehost\n");
   print(  "     mkauthkeys -r 'adB8fqeZs2d-gg+q joe\@somehost'\n");
   print(  "        remove the ssh key generated for user joe at somehost\n");
   print(  "     mkauthkeys -r 'joe\@somehost'\n");
   print(  "        remove all ssh keys generated for user joe at somehost\n\n");
}

sub Append_String {
   my ($str) = $_[0];

   open(OUTPUT_FILE,">>$output_file");
   print OUTPUT_FILE "$str\n";
   close(OUTPUT_FILE);

   return;
}

sub Remove_String {
   my ($str) = $_[0];
   my ($tmpfile) = "__mkauthkeystmpfile__";

   # Copy output_file to temp file.
   #
   $rc = system("cp $output_file $tmpfile");

   # If copy was successful, remove all strings matching input pattern.
   #
   if ($rc == 0) {
      open(OUTPUT_FILE,">$output_file");
      open(TMP_FILE,"<$tmpfile");
      foreach $line (<TMP_FILE>) {
         #print("\n line=$line=");
         print OUTPUT_FILE $line if ($line !~ m/$str/);
      }
      close(TMP_FILE);
      unlink($tmpfile);
      close(OUTPUT_FILE);
   } else {
      print("\n Unable to copy $output_file to temporary location\n\n");
   }

   return;
}
